using System;
using System.Net;
using System.Reactive.Linq;
using System.Xml;
using Wulong.Phone.Utils.Xml;

namespace Wulong.Phone.Utils
{
    public class BingMapper
    {

        public static IObservable<BingBackgroundItem> FetchBingBackgroundItems(int daysAgo, string mkt)
        {
            const string BingBackgroundUrl =
            "http://wwww.bing.com/HPImageArchive.aspx?format=xml&idx=0&n={0}&mkt={1}";
            return Observable.Return((HttpWebRequest)WebRequest.Create(string.Format(BingBackgroundUrl, daysAgo, mkt)))
                .SelectMany(request => Observable.FromAsyncPattern<WebResponse>(
                    request.BeginGetResponse, request.EndGetResponse)())
                .SelectMany(response =>
                                {
                                    var reader = XmlReader.Create(response.GetResponseStream());
                                    return XmlMapper.GetItem<BingBackgroundItem>(reader, "image");
                                })
                ;  
        }
    }
}
